import { AppDataSource } from "../data-source";
import { Photo } from "../entity/Photo";

export const factoryPhoto = async () => { 
  let photo = new Photo();
  photo.name = "Me and Bears";
  photo.description = "I am near polar bears";
  photo.filename = "photo-with-bears.jpg";
  photo.views = 1;
  photo.isPublished = true;
  const photoRepository = AppDataSource.getRepository(Photo)
  await photoRepository.save(photo)
  console.log("Saved a new photo with id: " + photo.id)

  console.log("Loading photos from the database...")
  // const photos = await photoRepository.find()

  // console.log("Loaded photos: ", photos)
}

export const searchPhoto = async () => {
  const photoRepository = AppDataSource.getRepository(Photo)

  const allPhotos = await photoRepository.find()
  console.log('allPhotos', allPhotos)

  const onePhoto = await photoRepository.findOneBy({ id: 2 })
  console.log('onePhoto', onePhoto)

  const meAndBearsPhoto = await photoRepository.findOneBy({ name: 'Me and Bears' })
  console.log('meAndBearsPhoto :>> ', meAndBearsPhoto);

  const allViewedPhotos = await photoRepository.findBy({ views: 1 })
  console.log("All viewed photos: ", allViewedPhotos)

  const allPublishedPhotos = await photoRepository.findBy({ isPublished: true })
  console.log("All published photos: ", allPublishedPhotos)

  const [photos, photosCount] = await photoRepository.findAndCount()

  console.log("All photos: ", photos)
  console.log("Photos count: ", photosCount)
}

export const updatePhoto = async () => { 
  const photoRepository = AppDataSource.getRepository(Photo)
  const photoToUpdate = await photoRepository.findOneBy({
    id: 1,
  })
  photoToUpdate.name = "Me, my friends and polar bears"
  await photoRepository.save(photoToUpdate)
  const photo = await photoRepository.findOneBy({
    id: 1,
  })
  console.log('photo :>> ', photo.name);
}

export const removePhoto = async () => {

  const photoRepository = AppDataSource.getRepository(Photo)


  const count1 = await photoRepository.count()
  console.log('count1 :>> ', count1);
  const photoToRemove = await photoRepository.findOneBy({
    id: 1,
  })

  await photoRepository.remove(photoToRemove)
  const count2 = await photoRepository.count()
  console.log('count2 :>> ', count2);
  
}